package com.binvshe.binvshe.literature;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.TextView;

import com.binvshe.binvshe.R;
import com.binvshe.binvshe.common.http.DataRequestListener;
import com.binvshe.binvshe.common.http.MyHttpRequest;
import com.binvshe.binvshe.common.http.UrlCenter;
import com.binvshe.binvshe.release.ReleaseEditArticalActivity;
import com.pachong.android.baseuicomponent.CompState;
import com.pachong.android.baseuicomponent.activity.SwipeListActivity;
import com.pachong.android.baseuicomponent.adapter.RecyclerViewBaseAdapter;
import com.pachong.android.framework.httprequest.IHttpRequest;
import com.pachong.android.frameworkbase.utils.EasyToast;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;

/**
 * 连载小说章节列表
 *
 * @Author: Weiwei Peng
 * @E-mail: pengveivei@sina.cn
 * @CreateDate: 2017/1/3 15:38
 * @Version: 1.0.0
 */
public class LiteratureChapterListActivity extends SwipeListActivity {
    public static final int TYPE_SERIAL = 0X01; // 连载
    public static final int TYPE_SINGLE = 0X02;  // 单篇
    private int type = TYPE_SINGLE;
    private ArticalBean articalBean;

    public static void start(Context context, int type, ArticalBean artical) {
        Intent intent = new Intent(context, LiteratureChapterListActivity.class);
        intent.putExtra("type", type);
        intent.putExtra("artical", artical);
        context.startActivity(intent);
    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        articalBean = (ArticalBean) getIntent().getSerializableExtra("artical");

        setPullToRefreshEnable(false);
        type = getIntent().getIntExtra("type", TYPE_SINGLE);
        setTitle(articalBean.getTitle());
        enableBackButton();

        getCustomToolbar().addRightButton("删除整部", new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                reqDelete();
            }
        });
        startLoading();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQ_CODE && resultCode == RESULT_OK) {
            int type = data.getIntExtra("type", ReleaseEditArticalActivity.TYPE_SINGLE);
            String title = data.getStringExtra("title");
            String content = data.getStringExtra("content");
            String articalId = data.getStringExtra("articalId");

            if (type == ReleaseEditArticalActivity.TYPE_SINGLE) {
                articalBean.setTitle(title);
                articalBean.setContent(content);
                startLoading();

            } else {
                List<ArticalBean.ChaptersBean> list = getData();
                if (list != null && list.size() > 0) {
                    for (ArticalBean.ChaptersBean bean : list) {
                        if (TextUtils.equals("" + bean.getId(), articalId)) {
                            bean.setTitle(title);
                            bean.setContent(content);
                            startLoading();
                            break;
                        }
                    }
                }

            }
            setTitle(title);
        }
    }

    private void reqDelete() {
        String url = UrlCenter.ARTICLE + "/" + articalBean.getId();
        IHttpRequest request = new MyHttpRequest(this);
        request.delete(url, null, new DataRequestListener<String>(String.class) {

            @Override
            public void onSuccess(String acct) {
                super.onSuccess(acct);
                setState(CompState.DATA);
                EasyToast.showToast(LiteratureChapterListActivity.this, "删除成功！");
                finish();

            }

            @Override
            public void onFailure(Throwable t, int errorNo, String strMsg) {
                super.onFailure(t, errorNo, strMsg);
                setState(CompState.DATA);
                EasyToast.showToast(LiteratureChapterListActivity.this, strMsg);
            }
        });
    }

    @Override
    public RecyclerViewBaseAdapter createAdapter() {
        return new TemplateListAdapter(this);
    }

    @Override
    public void onStartLoading() {
        getAdapter().getData().clear();
        getAdapter().notifyDataSetChanged();

        List<ArticalBean.ChaptersBean> list;
        if (type == TYPE_SINGLE) {
            list  = new ArrayList<>();
            ArticalBean.ChaptersBean bean = new ArticalBean.ChaptersBean();
            bean.setId(articalBean.getId());
            bean.setTitle(articalBean.getTitle());
            bean.setContent(articalBean.getContent());
            list.add(bean);
        } else {
            list = articalBean.getChapters();
        }

        if (list != null && list.size() > 0) {
            getAdapter().getData().addAll(list);
            getAdapter().notifyDataSetChanged();
            setState(CompState.DATA);
        } else {
            setState(CompState.EMPTY);
        }

    }

    public static final int REQ_CODE = 0XD;
    @Override
    public void onItemClick(AdapterView<?> arg0, View arg1, int position, long itemId) {
        ArticalBean.ChaptersBean bean = (ArticalBean.ChaptersBean) getData().get(position);
        Intent intent = new Intent();

        if (type == TYPE_SINGLE) {
            ReleaseEditArticalActivity.startEdit(this, REQ_CODE, ReleaseEditArticalActivity.TYPE_SINGLE, "" + bean.getId(), bean.getTitle(), bean.getContent());
        } else {
            ReleaseEditArticalActivity.startEdit(this, REQ_CODE, ReleaseEditArticalActivity.TYPE_SERIAL, "" + bean.getId(), bean.getTitle(), bean.getContent());
        }
    }

    /**
     * Adapter
     */
    public class TemplateListAdapter extends RecyclerViewBaseAdapter<ArticalBean.ChaptersBean> {

        public TemplateListAdapter(Context con) {
            super(con);
        }

        @Override
        public RecyclerView.ViewHolder onCreateHolder(ViewGroup viewGroup, int i) {
            return new ItemViewHolder(setAdapterViewItem(viewGroup, R.layout.list_item_literature_all_serials));
        }


        @Override
        public void onBindHolder(RecyclerView.ViewHolder viewHolder, int i) {
            ItemViewHolder holder = (ItemViewHolder) viewHolder;
            final ArticalBean.ChaptersBean bean = getData().get(i);
            holder.tvTitle.setText(bean.getTitle());

            if (type == TYPE_SERIAL) {
                holder.btnDelete.setVisibility(View.VISIBLE);
                holder.btnEdit.setVisibility(View.VISIBLE);
                holder.btnDelete.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        reqDeleteChapter(bean);
                    }
                });
                holder.btnEdit.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        ReleaseEditArticalActivity.startEdit(LiteratureChapterListActivity.this, REQ_CODE, ReleaseEditArticalActivity.TYPE_SERIAL, "" + bean.getId(), bean.getTitle(), bean.getContent());
                    }
                });

            } else {
                holder.btnDelete.setVisibility(View.GONE);
                holder.btnEdit.setVisibility(View.GONE);

            }
        }

        class ItemViewHolder extends RecyclerView.ViewHolder {
            @Bind(R.id.tvTitle)
            TextView tvTitle;
            @Bind(R.id.btnDelete)
            Button btnDelete;
            @Bind(R.id.btnEdit)
            Button btnEdit;

            ItemViewHolder(View view) {
                super(view);
                ButterKnife.bind(this, view);
            }
        }
    }

    private void reqDeleteChapter(final ArticalBean.ChaptersBean bean) {
        String url = String.format(UrlCenter.CHAPTER, "" + bean.getId());
        IHttpRequest request = new MyHttpRequest(this);
        request.delete(url, null, new DataRequestListener<String>(String.class) {

            @Override
            public void onSuccess(String acct) {
                super.onSuccess(acct);
                setState(CompState.DATA);
                getAdapter().getData().remove(bean);
                getAdapter().notifyDataSetChanged();
            }

            @Override
            public void onFailure(Throwable t, int errorNo, String strMsg) {
                super.onFailure(t, errorNo, strMsg);
                setState(CompState.DATA);
                EasyToast.showToast(LiteratureChapterListActivity.this, strMsg);
            }
        });
    }

}